<template>
  <div class="container">
    <!--头部筛选 start-->
    <div class="flex-row justify-between p_b10">
      <div>
        <el-input size="small" v-model="params.filter" placeholder="搜索关键词..." class="m_r10 width200"></el-input>
        <el-button size="small" type="primary" icon="el-icon-search" @click="onPageChange(1)"></el-button>
        <el-button size="small" type="primary" @click="onPageChange(1)">刷新</el-button>
      </div>
      <div>
        <!--<el-button size="small" type="primary" @click="toggleEditorModal(true)">新增商品</el-button>-->
      </div>
    </div>
    <!--头部筛选 end-->

    <!--列表数据 start-->
    <el-table :data="tableData" border size="mini">
      <el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
      <el-table-column prop="carId" :min-width="300" label="车辆信息">
        <template v-slot="{row}">

          <div class="flex-row align-center">
            <img alt="" :src="row.car.images[0]" class="car-image" v-if="row.car&&row.car.images"/>
            <div>
              【{{ row.car.carNumber }}】
              {{ row.car.brand }}.
              {{ row.car.model }}.
              {{ row.car.colour }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="carId" :min-width="200" label="租客" v-if="isAdmin">
        <template v-slot="{row}">

          <div class="flex-row align-center">
            <img alt="" :src="row.user.headImg" class="user-cover" v-if="row.user&&row.user.headImg"/>
            <div>
              {{ row.user.name }}
              （{{ row.user.phone }}）
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="carId" :min-width="200" label="服务包">
        <template v-slot="{row}">
          <el-tag
              size="small"
              class="m_r5 m_y2"
              v-for="(item,i) of row.carServerList||[]"
              :key="i">{{ item.name }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="days" :min-width="140" align="center" label="租赁时间（天）"></el-table-column>
      <el-table-column prop="totalPrice" :min-width="140" align="center" label="租金（元）"></el-table-column>
      <el-table-column prop="price" :min-width="120" align="center" label="状态">
        <template v-slot="{row}">
          <el-tag type="success" v-if="row.status===1">成功预约</el-tag>
          <el-tag type="danger" v-else-if="row.status===2">拒绝的预约</el-tag>
          <el-tag type="info" v-else-if="row.status===3">完成预约</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="startTime" :min-width="180" align="center" label="开始时间">
        <template v-slot="{row}">
          {{ format(row.startTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="comment" :min-width="200" label="评价"></el-table-column>
      <el-table-column prop="memo" :min-width="200" label="备注"></el-table-column>

      <el-table-column label="操作" :width="isAdmin?200:100" align="center" fixed="right">
        <template #default="{row}">
          <template v-if="isAdmin">
            <el-button
                type="success"
                plain round
                v-if="row.status===1"
                @click="onComplete(row)" size="mini">
              完成订单
            </el-button>
          </template>
          <template v-else>
            <el-button
                plain round
                type="success"
                v-if="row.status===3&&(!row.comment||row.comment.length===0)"
                @click="toggleCommentModal(true, row)" size="mini">
              评论
            </el-button>
            <el-tooltip v-else :content="row.status===3?'您已经评论过了':'该订单暂时无法评论'">
              <span class="m_x5">
                <el-button disabled plain round type="success" size="mini">
                  评论
                </el-button>
              </span>
            </el-tooltip>
          </template>


        </template>
      </el-table-column>
    </el-table>
    <!--列表数据 end-->


    <!--分页组件 start-->
    <div class="pagination">
      <el-pagination
          background layout="total, prev, pager, next"
          :current-page="pageMeta.current_page"
          :page-size="pageMeta.limit" :total="pageMeta.total"
          @current-change="onPageChange"></el-pagination>
    </div>
    <!--分页组件 end-->


    <!--评论弹框 start-->
    <el-dialog
        v-model="commentFormData.show"
        title="评论"
        width="50%">
      <el-form label-position="top" label-width="120px">
        <el-form-item label="">
          <el-input
              type="textarea"
              v-model="commentFormData.content"
              placeholder="您的使用体验..."
              show-word-limit
              maxlength="200"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="toggleCommentModal(false)">取消</el-button>
          <el-button size="small" type="primary" @click="onComment()">提交评论</el-button>
        </div>
      </template>
    </el-dialog>
    <!--评论弹框 end-->
  </div>


</template>

<script>
import {defineComponent, reactive, ref, toRaw} from "vue"
import {usePageMeta} from "../../hooks/usePageTableData";
import {deepClone, isEmpty} from "../../utils/helpers";
import Toast from "../../utils/Toast";
import Orders from "../../api/modules/Orders";
import {useStore} from "vuex";
import dayjs from "dayjs";

export default defineComponent({
  name: "Orders",
  data() {
    return {
      rules: {
        name: [
          {required: true, message: "请填写名称"}
        ],
        price: [
          {required: true, message: "请填写价格"},
          {type: 'number', min: 0, max: 99999, transform: v => Number(v) || '', message: "价格范围在0~99999之间"},
        ]
      },
    }
  },
  methods: {
    format(time, layout = 'YYYY-MM-DD HH:mm:ss') {
      return dayjs(time).format(layout)
    }
  },
  setup() {
    const store = useStore();
    const formRefName = ref(null);
    const pageHandle = usePageMeta(); // 分页相关数据
    const params = reactive({ // 筛选条件
      filter: "",
    });
    const tableData = ref([]); // 接口返回的数据列表

    onPageChange(1); // 初始化时直接请求一次分类列表


    const commentFormData = reactive({ // 评论表单数据（提交评论时使用）
      show: false, // 是否打开评论弹框
      row: {}, // 评论的订单数据行
      content: "" // 评论内容
    });

    /**
     * 打开、关闭评论框
     * @param show {boolean} true:打开 false 关闭
     * @param row
     */
    function toggleCommentModal(show, row = {}) {
      commentFormData.show = show;
      commentFormData.row = row;
      commentFormData.content = "";

    }


    // 提交评论
    async function onComment() {
      if (isEmpty(commentFormData.content.trim())) {
        Toast.warning('请填写评论内容')
        return
      }
      try {
        const res = await Orders.comment({
          commentContent: commentFormData.content,
          orderId: commentFormData.row.id,
          userId: commentFormData.row.userId,
        });
        Toast.success(res.message || '提交成功');
        toggleCommentModal(false)
        onPageChange(); // 评论成功(刷新列表数据)
      } catch (e) {
        console.log(e)
        Toast.error(e.message || '提交失败')
      }
    }

    /**
     * 获取订单列表数据
     * @param page page===undefined时表示刷新当前页面
     * @returns {Promise<void>}
     */
    async function onPageChange(page) {
      const pageMeta = deepClone(toRaw(pageHandle.pageMeta.value));
      if (page) {
        pageMeta.index = page;
      }
      try {
        const _params = {
          ...pageMeta, // 分页数据（当前页数，每页请求数量等）
          ...params, // 筛选参数（搜索条件等）
        };
        if (!store.state.user.isAdmin) { // 非管理员时仅可获取当前用户的订单
          _params.userId = store.state.user.userInfo.id;
        }
        const {data} = await Orders.lists(_params);
        tableData.value = (data.data || []).map(item => {
          if (item.car) {
            try {
              // 对每一项目中存在的车辆图片json字符串 转换为json数组
              item.car.images = JSON.parse(item.car.images);
            } catch (e) {

            }
          }
          return item;
        });
        // 请求到数据，更新公共的分页数据页码数
        pageHandle.updatePageMeta(pageMeta.index, data.count);

      } catch (e) {
        console.log(e);
      }
    }

    // 管理员完成订单按钮提交
    async function onComplete(row) {
      try {
        if (row.status !== 1) {
          throw new Error('无须处理该订单');
        }
        const {message} = await Orders.setStatus({
          id: row.id,
          status: 3,
        });
        Toast.success(message);
        onPageChange(); // 完成订单操作成功（刷新列表页面数据）
      } catch (e) {
        Toast.error(e.message || '操作失败')
      }
    }

    return {
      ...pageHandle,
      commentFormData,
      toggleCommentModal,
      params,
      onComment,
      isAdmin: store.state.user.isAdmin,
      onComplete,
      formRefName,
      tableData,
      onPageChange,
    }
  },
})
</script>

<style lang="scss" scoped>
.car-image {
  width: 60px;
  height: 40px;
}

.user-cover {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}
</style>
